package com.xjtu.platform.security.updatePassword;

import com.xjtu.platform.common.CommonService;
import com.xjtu.platform.common.CurrentUser;
import com.xjtu.platform.common.Result;
import com.xjtu.platform.common.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/security/updatePassword")
public class UpdatePasswordAPI {

    @Resource
    private UpdatePasswordService updatePasswordService;

    @Resource
    private CommonService commonService;

    @PostMapping("")
    public Result updatePassword(@RequestBody UpdatePasswordDto updatePasswordDto, @RequestHeader("Token") String token){
        String user_id = getCurrentUserIdByToken(token);
        int flag = updatePasswordService.getFlag(user_id);
//        System.out.println("abcdefg");
        long currentTime = System.currentTimeMillis();
        System.out.println(currentTime);
        long cachetime = updatePasswordService.getCachetime(user_id);
        System.out.println(cachetime);
        if(currentTime - cachetime <= 600000) {
            if (flag == updatePasswordDto.getUserCode()) {
                boolean ok = updatePasswordService.updatePwd(updatePasswordDto, user_id);
                if (ok) {
                    return Result.success("修改密码成功!!!");
                } else {
                    return Result.fail(Result.ERR_CODE_SYS, "系统维护中.......");
                }
            } else {
                return Result.fail(Result.ERR_CODE_SYS, "验证码错误");
            }
        }else{
            return Result.fail(Result.ERR_CODE_SYS, "验证码时间超过10分钟");
        }
    }

    @GetMapping("/getEmail")
    public Result getEmail(@RequestHeader("Token") String token){
        String user_id = getCurrentUserIdByToken(token);
        UserDto userDto = new UserDto();
        Map<String,Object> page = updatePasswordService.getEmail(userDto,user_id);
        return Result.success(page);
    }

    public String getCurrentUserIdByToken(String token)
    {
        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);
        System.out.println(currentUser);
        return currentUser.getUserId();
    }
}
